package com.demo1105.filter;

import com.demo1105.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//如果用户没有登录，则不允许访问admin下的所有内容
//拦截一个路径下的所有资源：包括html css js jpg等前端资源 以及后端servlet请求路径
@WebFilter(urlPatterns = "/demo1105/admin/*")
public class AdminFilter implements Filter {
    public AdminFilter() {
        System.out.println("AdminFilter 构造函数执行");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化方法 执行");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("拦截器拦截成功！doFilter 方法执行");
        //如何在这里添加 登录才能访问的逻辑？
        //1.获取session对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        //2.拿到User对象
        User user = (User) session.getAttribute("user");
        if (user == null) {
            //没有登录
        } else {
            //这行代码是放行的标志
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("AdminFilter 过滤器被销毁");
    }
}
